﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Diagnostics;
using System.Deployment.Application;
using CCF20Model;
using IWshRuntimeLibrary;
using System.Reflection;
using WiseLinkWPF.Windows.Controls;

namespace CCF20
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    /// 
    public partial class App : System.Windows.Application
    {
        private int exceptionCount = 0;
        static string zicUrl = string.Empty;
        static bool isJava = false;
        public static string AllowedPermission = string.Empty;
        public static string CurrentUser = string.Empty;
        
        public static string ZICUrl
        {
            get
            {
                return zicUrl;
            }
        }
        public static bool IsJava
        {
            get
            {
                return isJava;
            }
        }
        
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception.Message.Contains("里程，周期不可同时为空"))
            {
                MessageBox.Show("里程，周期不可同时为空");
                return;
            }
            exceptionCount ++;
            if (exceptionCount > 11)
            {
                App.Current.Shutdown();
            }
            LoggerHelper.LogCCF20(string.Format("[Exception:]{0} \t [Stack:] {1}",
                                           e.Exception.Message,
                                           e.Exception.StackTrace));
            if (e.Exception.Message.Contains("The underlying provider failed on Open"))
            {
                MessageBox.Show("CCF2.0 无法连接数据库，请检查系统配置!", "请注意", MessageBoxButton.OK);
                App.Current.Shutdown();
            }

            if (e.Exception.InnerException != null)
            {
                LoggerHelper.LogCCF20(string.Format("[Inner Exception:]{0} \t [Stack:] {1}",
                    e.Exception.InnerException.Message,
                    e.Exception.InnerException.StackTrace ?? ""));
            }
            e.Handled = true;
            MessageBox.Show("CCF2.0 运行出现意外。 请将日志文件发送给智信通!", "请注意", MessageBoxButton.OK);
            
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            LoggerHelper.LogCCF20("CCF20 Started");
            CheckConfiguration();
            CreateShortCutForZICMonitor();
            LocalizationManager.Manager = new CustomLocalizationManager();
            
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            LoggerHelper.FlushLog();
        }

        public static void CheckConfiguration()
        {
            string myConfigPath;
            bool IsChanged = false;
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                myConfigPath = ApplicationDeployment.CurrentDeployment.DataDirectory;
                LoggerHelper.LogCCF20("IsNetworkDeployed");
            }
            else
            {
                myConfigPath = ".";
            }
            
            myConfigPath += "\\CCFConfiguration.xml";
            LoggerHelper.LogCCF20(string.Format("配置文件路径:{0}",myConfigPath));
            AppConfig ccfConfig = new AppConfig("CCF20.exe.config");
            AppConfig myConfig = new AppConfig(myConfigPath);
            AppConfig zicConfig = new AppConfig("ZICMonitor.exe.config");

            string ccfConnection = ccfConfig.GetValue("CCF20Entities", "connectionStrings", "connectionString");
            string aspnetConnection = ccfConfig.GetValue("AspnetMembershipConnectionString", "connectionStrings", "connectionString");
            string zicConnection = zicConfig.GetValue("CCF20Entities", "connectionStrings", "connectionString");
            string ccfConnectionTemplate= "metadata=res://*/CCF20Model.csdl|res://*/CCF20Model.ssdl|res://*/CCF20Model.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};Initial Catalog={1};User Id={2};Password={3}'";
            string aspnetMembershipTemplate = "Data Source={0};Initial Catalog={1};User Id={2};Password={3};";
            string myConfigConnection = string.Format(ccfConnectionTemplate,
                                                        myConfig.GetValue("database","appSettings",  "value"),
                                                        myConfig.GetValue("catalog", "appSettings", "value"),
                                                        myConfig.GetValue("user", "appSettings", "value"),
                                                        myConfig.GetValue("password", "appSettings", "value"));
            string aspnetConfigConnection = string.Format(aspnetMembershipTemplate,
                                                        myConfig.GetValue("database", "appSettings", "value"),
                                                        myConfig.GetValue("catalog", "appSettings", "value"),
                                                        myConfig.GetValue("user", "appSettings", "value"),
                                                        myConfig.GetValue("password", "appSettings", "value"));

            if (!aspnetConnection.Equals(aspnetConfigConnection,StringComparison.OrdinalIgnoreCase))
            {
                ccfConfig.SetValue("AspnetMembershipConnectionString", "connectionStrings", "connectionString", aspnetConfigConnection);
                ccfConfig.SaveConfigDoc();
                IsChanged = true;
            }
           
            if (!ccfConnection.Equals(myConfigConnection))
            {
                ccfConfig.SetValue("CCF20Entities", "connectionStrings", "connectionString",myConfigConnection);
                ccfConfig.SaveConfigDoc();
                IsChanged = true;
            }
            if (!zicConnection.Equals(myConfigConnection))
            {
                zicConfig.SetValue("CCF20Entities", "connectionStrings", "connectionString", myConfigConnection);
                zicConfig.SaveConfigDoc();
                IsChanged = true;
            }
            string logdir = myConfig.GetValue("logdir","appSettings",  "value").ToLower();
            
            if (!ccfConfig.GetValue("CCF20Log", "listeners", "fileName").ToLower().Equals(string.Format("{0}\\ccf20.log",logdir.ToLower())))
            {
                ccfConfig.SetValue("CCF20Log", "listeners", "fileName",string.Format("{0}\\ccf20.log", logdir));
                ccfConfig.SaveConfigDoc();
                IsChanged = true;
            }
            if (!zicConfig.GetValue("ZICDebug", "listeners", "fileName").ToLower().Equals(string.Format("{0}\\zicdebug.log", logdir.ToLower())))
            {
                zicConfig.SetValue("ZICDebug", "listeners", "fileName", string.Format("{0}\\zicdebug.log", logdir));
                zicConfig.SetValue("ZICMonitor", "listeners", "fileName", string.Format("{0}\\zicmonitor.log", logdir));
                zicConfig.SaveConfigDoc();
                IsChanged = true;
            }
            if (IsChanged)
            {
                MessageBox.Show("CCF的配置文件刚刚更新，请从新启动!", "CCF20", MessageBoxButton.OK);
                
                App.Current.Shutdown();
            }
            
            if (!bool.TryParse(myConfig.GetValue("isjava", "appSettings", "value"), out isJava))
            {
                MessageBox.Show("是否一汽大众的配置有错，请确认后从新启动!", "CCF20", MessageBoxButton.OK);
                App.Current.Shutdown();
            }
            zicUrl = myConfig.GetValue("zicurl", "appSettings", "value");
            
        }
        static void CreateShortCutForZICMonitor()
        {
            WshShellClass shell = new WshShellClass();
            string desktopPath = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\ZicMonitor.lnk");
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(desktopPath);
            Assembly code = Assembly.GetExecutingAssembly();
            shortcut.TargetPath = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("CCF20.exe", "ZicMonitor.exe");
            shortcut.Description = "ZICMonitor ";
            shortcut.Save();

            

            
            string company = string.Empty;
            if (Attribute.IsDefined(code, typeof(AssemblyCompanyAttribute)))
            {
                AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(code,typeof(AssemblyCompanyAttribute));
                company = ascompany.Company;
            }
            string programMenuPath = string.Empty;
            programMenuPath = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs),"\\", company,"\\","ZicMonitor.lnk");
            System.IO.File.Copy(desktopPath, programMenuPath, true);




        }
    }
    
    
}
